using System;
using Dimebrain.TweetSharp.Core.Caching;

#if !SILVERLIGHT

#endif

namespace Dimebrain.TweetSharp.Core.Web.Query
{
    partial class WebQueryBase
    {
        // expects real cache key, not prefix
        private void ExecuteGetAsyncAndCache(IClientCache cache, string key, string url, IWebQueryClient client)
        {
            var fetch = cache.Get<string>(key);

            if (fetch != null)
            {
                var args = new WebQueryResponseEventArgs(fetch);
                OnQueryResponse(args);
            }
            else
            {
                var state = new Pair<IClientCache, string>
                            {
                                First = cache,
                                Second = key
                            };

                client.OpenReadCompleted += client_OpenReadCompleted;
                client.OpenReadAsync(new Uri(url), state);
            }
        }

        // expects real cache key, not prefix
        private void ExecuteGetAsyncAndCacheWithExpiry(IClientCache cache, string key, string url, DateTime absoluteExpiration, IWebQueryClient client)
        {
            var fetch = cache.Get<string>(key);
            
            if (fetch != null)
            {
                var args = new WebQueryResponseEventArgs(fetch);
                OnQueryResponse(args);
            }
            else
            {
                var state = new Pair<IClientCache, Pair<string, DateTime>>
                            {
                                First = cache,
                                Second = new Pair<string, DateTime> { First = key, Second = absoluteExpiration }
                            };

                client.OpenReadCompleted += client_OpenReadCompleted;
                client.OpenReadAsync(new Uri(url), state);
            }
        }

        // expects real cache key, not prefix
        private void ExecuteGetAsyncAndCacheWithExpiry(IClientCache cache, string key, string url, TimeSpan slidingExpiration, IWebQueryClient client)
        {
            var fetch = cache.Get<string>(key);

            if (fetch != null)
            {
                var args = new WebQueryResponseEventArgs(fetch);
                OnQueryResponse(args);
            }
            else
            {
                var state = new Pair<IClientCache, Pair<string, TimeSpan>>
                            {
                                First = cache,
                                Second = new Pair<string, TimeSpan> { First = key, Second = slidingExpiration }
                            };

                client.OpenReadCompleted += client_OpenReadCompleted;
                client.OpenReadAsync(new Uri(url), state);
            }
        }
    }
}